package com.zhuj.handler;

import com.zhuj.codec.NrpcJsonDecode;
import com.zhuj.codec.NrpcJsonEncode;
import com.zhuj.codec.NrpcProtostuffDecode;
import com.zhuj.codec.NrpcProtostuffEncode;
import com.zhuj.core.InitNrpc;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Created by Administrator on 2018/1/3.
 */
public class RpcChannelInitializer extends ChannelInitializer<SocketChannel>{

    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
//        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        if ("json".equals(InitNrpc.getCodec())){
            pipeline.addLast(new StringDecoder());
            pipeline.addLast(new LineBasedFrameDecoder(68*1024));
            pipeline.addLast(new NrpcJsonDecode(false));
            pipeline.addLast(new StringEncoder());
            pipeline.addLast(new NrpcJsonEncode());
        }else if ("protobuf".equals(InitNrpc.getCodec())){
            pipeline.addLast(new NrpcProtostuffDecode(false));
            pipeline.addLast(new NrpcProtostuffEncode());
        }
        pipeline.addLast(new ServerHandler());
    }

}
